<?php
namespace app\store\controller\shop;
use app\store\controller\Controller;
use app\store\model\Calling as CallingModel;
use app\store\model\Shop as ShopModel;

/**
 * 叫号器控制器
 */
class Calling extends Controller
{
    /**
     * 获取列表
     */
    public function index($shop_id='')
    {
        if(!$this->is_admin OR $this->shop_mode == 10){
            $shop_id = $this->shop_id;
        }
        $model = new CallingModel;
        $list = $model->getList($shop_id);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
        $model = new CallingModel;
        if (!$this->request->isAjax()) {
			$shop = new ShopModel;
			$shoplist = $shop->getList();
            return $this->fetch('add', compact('shoplist'));
        }
        // 新增记录
        $data = $this->postData('calling');
        if(!$this->is_admin OR $this->shop_mode == 10){
            $data['shop_id'] = $this->shop_id;
        }
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('shop.calling/index'));
        }
		$error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 更新
     */
    public function edit($calling_id)
    {
        $model = CallingModel::detail($calling_id);
        if (!$this->request->isAjax()) {
			$shop = new ShopModel;
			$shoplist = $shop->getList();
            return $this->fetch('edit', compact('model','shoplist'));
        }
        // 更新记录
        if ($model->edit($this->postData('calling'))) {
            return $this->renderSuccess('更新成功', url('shop.calling/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($calling_id)
    {
        $model = CallingModel::detail($calling_id);
        if ($model->remove()) {
            return $this->renderSuccess('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
    }

    /**
     * 开启/关闭
     */
    public function open($calling_id)
    {
        $model = CallingModel::detail($calling_id);
        $model->is_open = $model['is_open']['value']?0:1;
        if($model->save()){
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError('操作失败');
    }

}
